﻿using System;
using System.Collections.Generic;

namespace Core
{
    public class NumericWatcherComponent : Entity, IAwake
    {
        private readonly Dictionary<int, List<INumericWatcher>> all = new Dictionary<int, List<INumericWatcher>>();

        void IAwake.Awake()
        {
            var attribute = typeof(NumericWatcherAttribute);
            var types = World.GetComponent<CodeTypes>().GetTypes(attribute);
            foreach ((string _, Type type) in types)
            {
                object[] attrs = type.GetCustomAttributes(attribute, false);
                if (attrs.Length == 0)
                    continue;

                var numericWatcherAttribute = attrs[0] as NumericWatcherAttribute;

                if(!all.TryGetValue(numericWatcherAttribute.NumericType, out var list))
                {
                    list = new List<INumericWatcher>();
                    all[numericWatcherAttribute.NumericType] = list;
                }

                list.Add(Activator.CreateInstance(type) as INumericWatcher);
            }
        }

        public void Run(NumbericChange args)
        {
            if (!all.TryGetValue(args.NumericType, out var list))
                return;

            foreach (var watcher in list)
            {
                try
                {
                    watcher.Run(args);
                }
                catch(Exception ex)
                {
                    Log.Error(ex);
                }
            }
        }

    }
}